//
//  AFHTTPSessionManager+TG.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/5/5.
//

#import "AFHTTPSessionManager+TG.h"

@implementation AFHTTPSessionManager (TG)

- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(nullable id)parameters
                                         headers:(nullable NSDictionary <NSString *, NSString *> *)headers
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
                                         failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure
{
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
    if ([URLString isEqualToString:@"api/login"]) {
        NSString *paramsStr = [self postDataWithDic:parameters];
        NSData *body = [paramsStr dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:body];
    }
    for (NSString *headerField in headers.keyEnumerator) {
        [request setValue:headers[headerField] forHTTPHeaderField:headerField];
    }
    if (serializationError) {
        if (failure) {
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
        }

        return nil;
    }

    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [self dataTaskWithRequest:request
                          uploadProgress:uploadProgress
                        downloadProgress:downloadProgress
                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
        if (error) {
            if (failure) {
                failure(dataTask, error);
            }
        } else {
            if (success) {
                success(dataTask, responseObject);
            }
        }
    }];

    return dataTask;
}

- (NSString *)postDataWithDic:(NSDictionary *)dic {
    NSMutableString *dataStr = [NSMutableString string];
    for (int i = 0; i < dic.count;  i ++) {
        NSString *key = dic.allKeys[i];
        id value = dic[key];
        
        if ([value isKindOfClass:[NSString class]]) {
            [dataStr appendFormat:@"%@=%@&",key,value];
        }else if([value isKindOfClass:[NSDictionary class]]){
            
            NSDictionary *param = value;
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [dataStr appendFormat:@"%@=%@&",key,jsonString];
        }
    }
    return dataStr;
}

@end
